package com.yms.socket.server;

import com.yms.socket.SelectorUtil;
import com.yms.socket.client.DatagramChannelClient;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Scanner;
import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @version : 1.0
 * @author: yangmingsong
 * @date: 2022/7/20-07-20-16:42
 * @description: spring5Test
 */
public class DatagramChannelServer {
    private static Lock lock = new ReentrantLock();
    private static Condition readLock = lock.newCondition();
    private static Condition writeLock = lock.newCondition();
    private static Selector selector = SelectorUtil.getSelector();
    private  static DatagramChannel datagramChannel = null;
    private  static  ByteBuffer buffer = ByteBuffer.allocate(1024);
    static {

        try {
            datagramChannel = DatagramChannel.open().bind(new InetSocketAddress(8088));
            datagramChannel.configureBlocking(false);
            datagramChannel.register(selector, SelectionKey.OP_READ);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static void main(String[] args) throws IOException {
        try{
        while (selector.select() > 0 ){
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                if (key.isReadable()) {
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    datagramChannel.receive(byteBuffer);
                    String s0 = new String(byteBuffer.array(), "utf-8");
                    System.out.println(s0);
                }
            }
        }
    }catch (Exception e){
        e.getStackTrace();
    }
    }




}
